package com.briup.es.service.impl;

import com.briup.es.config.auth.SecurityUserContext;
import com.briup.es.config.exception.ServiceException;
import com.briup.es.config.response.ResultCode;
import com.briup.es.domain.bean.Address;
import com.briup.es.domain.vo.AddressVO;
import com.briup.es.mapper.AddressMapper;
import com.briup.es.mapper.UserMapper;
import com.briup.es.service.AddressService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@RequiredArgsConstructor
public class AddressServiceImpl implements AddressService {

    private final AddressMapper addressMapper;
    private final UserMapper userMapper;

    @Override
    public List<AddressVO> listAddressByUserId(Integer userId) {
        return addressMapper.listAddressByUserId(userId);
    }

    @Override
    public void modifyDefaultAddress(Integer addressId, String action) {
        // 根据地址id以及当前登录用户的id判断该地址是否属于当前用户
        Integer userId = SecurityUserContext.userId();
        Address address = addressMapper.queryByUserIdAndId(addressId,userId);
        if (address == null){
            throw new ServiceException(ResultCode.ADDRESS_IS_NOT_FOUND);
        }

        // 修改当前用户的默认地址
        if ("cancel".equals(action)){
            userMapper.setDefaultAddress(userId,null);
        }else {
            userMapper.setDefaultAddress(userId, addressId);
        }
    }
}
